<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">


<meta name="google-site-verification" content="E9deYnivN5MuHMuIfiMZZfS0alv-d_0UjcwjBL79lGU" />



<meta name="baidu-site-verification" content="iHYWJxscwD" />










<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="true" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="ETF,投资理财,定投,Python,数据分析," />










<meta name="description" content="作为一个80后的小伙，我错过了一次又一次让自己财富增加的机会，唯一的投资理财就是把钱通通放到某额宝里。一年前，我开始学习理财的知识，最后选择进行etf基金定投来投资。找了一家券商开了户。投资的品种就两个:300ETF和纳指ETF，分别追踪沪深300指数和纳斯达克指数。选择这两个指数之前我用python跑了一下历史数据，二者的相关性很低，也许可以做风险对冲？开始是每个月一次，后来逐渐增加到每个月三次">
<meta property="og:type" content="article">
<meta property="og:title" content="ETF基金定投数据分析">
<meta property="og:url" content="https://zwdnet.github.io/2019/01/12/ETF%E5%9F%BA%E9%87%91%E5%AE%9A%E6%8A%95%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/index.html">
<meta property="og:site_name" content="赵瑜敏的口腔医学专业学习博客">
<meta property="og:description" content="作为一个80后的小伙，我错过了一次又一次让自己财富增加的机会，唯一的投资理财就是把钱通通放到某额宝里。一年前，我开始学习理财的知识，最后选择进行etf基金定投来投资。找了一家券商开了户。投资的品种就两个:300ETF和纳指ETF，分别追踪沪深300指数和纳斯达克指数。选择这两个指数之前我用python跑了一下历史数据，二者的相关性很低，也许可以做风险对冲？开始是每个月一次，后来逐渐增加到每个月三次">
<meta property="og:locale">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/01.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/02.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/03.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/04.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/05.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/06.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/07.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/08.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/09.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/10.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/11.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/12.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/13.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/14.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/15.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg">
<meta property="article:published_time" content="2019-01-12T09:25:28.000Z">
<meta property="article:modified_time" content="2020-08-30T05:52:03.000Z">
<meta property="article:author" content="赵瑜敏">
<meta property="article:tag" content="ETF">
<meta property="article:tag" content="投资理财">
<meta property="article:tag" content="定投">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="数据分析">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/01.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zwdnet.github.io/2019/01/12/ETF基金定投数据分析/"/>





  <title>ETF基金定投数据分析 | 赵瑜敏的口腔医学专业学习博客</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">赵瑜敏的口腔医学专业学习博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zwdnet.github.io/2019/01/12/ETF%E5%9F%BA%E9%87%91%E5%AE%9A%E6%8A%95%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="赵瑜敏的口腔医学专业学习博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">ETF基金定投数据分析</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-01-12T09:25:28+00:00">
                2019-01-12
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E8%AE%A1%E7%AE%97%E6%9C%BA/" itemprop="url" rel="index">
                    <span itemprop="name">计算机</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2.9k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  11
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>作为一个80后的小伙，我错过了一次又一次让自己财富增加的机会，唯一的投资理财就是把钱通通放到某额宝里。一年前，我开始学习理财的知识，最后选择进行etf基金定投来投资。找了一家券商开了户。投资的品种就两个:300ETF和纳指ETF，分别追踪沪深300指数和纳斯达克指数。选择这两个指数之前我用python跑了一下历史数据，二者的相关性很低，也许可以做风险对冲？<br>开始是每个月一次，后来逐渐增加到每个月三次，隔十天左右进行一次。单纯买入，没有止盈止损。我计划是先这么投一年，再看结果来调整。截止2019年1月9日，账户收益情况如下:<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/01.jpg">亏的。前几天美股暴跌，亏得更多。近一年定投的感受就是，这种投资方式真的很考验人性，好几次我都想卖了，忍住了。<br>现在，我们就用Python来分析一下近一年来的投资数据吧。开发环境:由于条件限制，我是在安卓手机上用Pydroid3做编程环境的，Python版本3.6.2。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/02.jpg"> <br>常用的一些库都能安装，看自带的例子，似乎还能写安卓APP，我还没试过。与在电脑上编程相比，有两个限制:首先画图不能直接显示，要用savefig保存图片到文件;其次，深度学习的一些库，如Tensorflow等，装不了，可能是因为与硬件相关吧。但机器学习的库，如scikit-learn等，可以安装的。另外还安装了Termux等，用于进行git操作。<br>开发环境搞定了，接下来就是获取数据的问题了。我从券商的APP上把数据一个一个搬到Excel表格里，像这样:<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/03.jpg"><br>本来想就这么读了，发现还可以另存为csv文件。那更好。于是数据就有了。开工吧。先导入相关的库，然后用read_csv读入数据:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">from</span> pandas <span class="keyword">import</span> Series, DataFrame</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">#从csv文件读入数据</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">ImportData</span>(<span class="params">FileName</span>):</span></span><br><span class="line">    df = pd.read_csv(FileName)</span><br><span class="line">    <span class="keyword">return</span> df</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line"><span class="comment">#主程序</span></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    etfdata = ImportData(<span class="string">&quot;etfdata.csv&quot;</span>)</span><br><span class="line">    print(etfdata)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/04.jpg"><br>OK，没问题。<br>接下来就开始折腾数据吧。DataFrame是一种表格式的，含有多列的数据结构。每列的数据类型可以不一样。每行/每列数据都有一个索引。用DataFrame.columns()得到每列的索引。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#探索数据</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">ExploreData</span>(<span class="params">Data</span>):</span></span><br><span class="line">    <span class="comment">#每列的索引名称</span></span><br><span class="line">    print(Data.columns)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/05.jpg"><br>用每列索引名称可以提取相应列的数据</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">print(Data[<span class="string">&quot;成交金额&quot;</span>])</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/06.jpg"><br>还可以用”变量名.列名”的方式，结果是一样的。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">print(Data.成交金额)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/07.jpg"><br>还可以用相同的方式输出指定行的信息:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">print(Data.ix[<span class="number">1</span>])</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/08.jpg"><br>用values属性可以返回DataFrame的值。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#返回Data的值   </span></span><br><span class="line">print(Data.values)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/09.jpg"><br>现在，可以把原始数据按买入的etf分成两个了:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">#分离数据:根据买入的etf的不同划分数据</span><br><span class="line">def DivData(Data):</span><br><span class="line">    df_300 &#x3D; Data[Data[&quot;证券名称&quot;] &#x3D;&#x3D; &quot;300ETF&quot;]</span><br><span class="line">    df_nas &#x3D; Data[Data[&quot;证券名称&quot;] &#x3D;&#x3D; &quot;纳指ETF&quot;]</span><br><span class="line">    return (df_300, df_nas)</span><br><span class="line">    用describe描述数据特征</span><br><span class="line">#描述数据</span><br><span class="line">    print(df_300.describe())</span><br><span class="line">    print(df_nas.describe())</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/10.jpg">   <br>按成交均价，画个图看看吧。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">plt.plot(df_300[<span class="string">&quot;成交均价&quot;</span>])</span><br><span class="line">    plt.plot(df_nas[<span class="string">&quot;成交均价&quot;</span>])</span><br><span class="line">    plt.savefig(<span class="string">&quot;成交均价.png&quot;</span>)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/11.jpg"><br>OK，接下来要计算收益率等信息了，需要知道历史股价信息，用tushare库。这是国产的库，用来获取各种金融数据。官方版本已经到1.2.15了，我在pydroid3里装的是0.6.8，升级出现pyzmq错误，搜了半天没找到解决方法，就暂时用旧的那个好了。<br>用get_k_data函数，因为其日期数据是yyyy-mm-dd格式的，先转换一下。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#将八位数字的日期转换为yyyy-mm-dd</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">TransfDate</span>(<span class="params">d</span>):</span></span><br><span class="line">    year = <span class="built_in">int</span>(d/<span class="number">10000</span>)</span><br><span class="line">    month = <span class="built_in">int</span>((d - year*<span class="number">10000</span>)/<span class="number">100</span>)</span><br><span class="line">    day = <span class="built_in">int</span>((d - year*<span class="number">10000</span> - month*<span class="number">100</span>))</span><br><span class="line">    date = <span class="built_in">format</span>(<span class="string">&quot;%4d-%02d-%02d&quot;</span> % (year, month, day))</span><br><span class="line">    <span class="keyword">return</span> date</span><br></pre></td></tr></table></figure>
<p>转换函数留着备用。<br>先找出最早开始定投的时间:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">beginTime = df_300.成交日期.<span class="built_in">min</span>()</span><br><span class="line">endTime = df_300.成交日期.<span class="built_in">max</span>()</span><br></pre></td></tr></table></figure>
<p>然后就用tushare抓取历史数据</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#抓取历史数据</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">GetHistoryData</span>(<span class="params">Code, BeginTime, EndTime</span>):</span></span><br><span class="line">    df = ts.get_k_data(Code, index = <span class="literal">False</span>,  start = TransfDate(BeginTime), end = TransfDate(EndTime))</span><br><span class="line">    <span class="keyword">return</span> df</span><br></pre></td></tr></table></figure>
<p>输出一下看看</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">df_300_hist = GetHistoryData(<span class="string">&quot;510300&quot;</span>, beginTime, endTime)</span><br><span class="line">    df_nas_hist = GetHistoryData(<span class="string">&quot;513100&quot;</span>, beginTime, endTime)</span><br><span class="line">    print(df_300_hist)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/12.jpg"><br>没问题啦。现在就可以用历史数据计算定投的持仓收益情况了。这个要考虑一下计算方法：就从开始定投的交易日开始，每个交易日计算一次。根据每次交易的成交量和手续费，计算一个总投入。再根据买入股票的量，计算一个持仓量，根据持仓量就可以算出当前股票的市值。再减去总投入，就是总收益了。用收盘价计算吧。<br>先筛选下载的历史数据，只保留日期和收盘价。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">df_300_hist = df_300_hist.loc[<span class="number">0</span>:<span class="built_in">len</span>(df_300_hist), [<span class="string">&quot;date&quot;</span>, <span class="string">&quot;close&quot;</span>]]</span><br><span class="line">    df_nas_hist = df_nas_hist.loc[<span class="number">0</span>:<span class="built_in">len</span>(df_nas_hist), [<span class="string">&quot;date&quot;</span>, <span class="string">&quot;close&quot;</span>]]</span><br></pre></td></tr></table></figure>
<p>接下来就计算数据啦。出现很多问题，折腾半天，发现是原始数据中有同一天对同一只基金多次买入的问题。搞不定，最后用手工合并啦。<br>计算数据费了很多功夫，主要是因为不是每个交易日都有交易，而每个交易日股价都在变动，市值和收益率也在变动，因此交易记录和股价记录长度不一致，要换算。这是最长的一个函数了，一定还有更简洁的方法。我之前学的C/C++，c语言的”味道”很浓。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#根据投资记录和历史数据计算持仓收益率等数据。</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">Calculator</span>(<span class="params">inverstData, histData</span>):</span></span><br><span class="line">    i = <span class="number">0</span></span><br><span class="line">    j = <span class="number">0</span></span><br><span class="line">    vol = []    <span class="comment">#持仓股票数量</span></span><br><span class="line">    fee = []    <span class="comment">#手续费</span></span><br><span class="line">    money = []   <span class="comment">#投资总额</span></span><br><span class="line">    rate = []     <span class="comment">#收益率</span></span><br><span class="line">    time = []   <span class="comment">#时间</span></span><br><span class="line">    market = []  <span class="comment">#股票市值</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> date <span class="keyword">in</span> histData.date:</span><br><span class="line">        d1 = TransfDate2(date)</span><br><span class="line">        d2 = inverstData.成交日期[i]</span><br><span class="line">        b = (d1 == d2)</span><br><span class="line">        time.append(d1)</span><br><span class="line">        <span class="comment">#该日期有交易，改变数据</span></span><br><span class="line">        <span class="keyword">if</span> b == <span class="literal">True</span>:</span><br><span class="line">            <span class="keyword">if</span> i == <span class="number">0</span>: <span class="comment">#第一天，直接插</span></span><br><span class="line">                vol.append(inverstData.成交量[i])</span><br><span class="line">                fee.append(inverstData.手续费[i])</span><br><span class="line">                money.append(inverstData.发生金额[i])</span><br><span class="line">                market.append(vol[i]*histData.close[i])</span><br><span class="line">                <span class="comment">#计算收益率=市值/投资总额</span></span><br><span class="line">                rate.append(market[i]/money[i] - <span class="number">1.0</span>)</span><br><span class="line">            <span class="keyword">else</span>: <span class="comment">#不是第一天，但有交易</span></span><br><span class="line">                 vol.append(vol[j-<span class="number">1</span>] + inverstData.成交量[i])</span><br><span class="line">                 fee.append(fee[j-<span class="number">1</span>] + inverstData.手续费[i])</span><br><span class="line">                 money.append(money[j-<span class="number">1</span>] + inverstData.发生金额[i])</span><br><span class="line">                 market.append(vol[j]*histData.close[j])</span><br><span class="line">                 <span class="comment">#计算收益率=市值/投资总额</span></span><br><span class="line">                 rate.append(market[j]/money[j] -<span class="number">1.0</span>)</span><br><span class="line">            i = i+<span class="number">1</span></span><br><span class="line">        <span class="keyword">else</span>: <span class="comment">#没有交易，复制上一天的数据</span></span><br><span class="line">            vol.append(vol[j-<span class="number">1</span>])</span><br><span class="line">            fee.append(fee[j-<span class="number">1</span>])</span><br><span class="line">            money.append(money[j-<span class="number">1</span>])</span><br><span class="line">            market.append(vol[j]*histData.close[j])</span><br><span class="line">            rate.append(market[j]/money[j] - <span class="number">1.0</span>)</span><br><span class="line">        j = j+<span class="number">1</span></span><br><span class="line">    data = pd.DataFrame(&#123;</span><br><span class="line">    <span class="string">&quot;日期&quot;</span>:time,</span><br><span class="line">    <span class="string">&quot;持仓量&quot;</span>:vol,</span><br><span class="line">    <span class="string">&quot;手续费&quot;</span>:fee,</span><br><span class="line">    <span class="string">&quot;成本&quot;</span>:money,</span><br><span class="line">    <span class="string">&quot;市值&quot;</span>:market,</span><br><span class="line">    <span class="string">&quot;收益率&quot;</span>:rate&#125;)</span><br><span class="line">    <span class="keyword">return</span> data</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/13.jpg"><br>搞定！再把收益率趋势图画出来。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">plt.figure()</span><br><span class="line">    plt.plot(data_300.收益率, label = <span class="string">&quot;300etf&quot;</span>)</span><br><span class="line">    plt.plot(data_nas.收益率, label = <span class="string">&quot;纳指etf&quot;</span>)</span><br><span class="line">    plt.legend(loc = <span class="string">&quot;upper right&quot;</span>)</span><br><span class="line">    plt.savefig(<span class="string">&quot;收益率.png&quot;</span>)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/14.jpg"><br>美股跟a股相关性果然很低。接下来就是具体折腾数据啦。先把两个股票的数据合并一下，算出一个总持仓的收益数据。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#合并两个数据，算出总的持仓收益率等数据</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">MergeData</span>(<span class="params">data1, data2, histData1, histData2</span>):</span></span><br><span class="line">    <span class="comment">#合并日期，持仓金额，手续费,市值，并计算持仓收益率</span></span><br><span class="line">    money = [] <span class="comment">#成本</span></span><br><span class="line">    fee = [] <span class="comment">#手续费总额</span></span><br><span class="line">    market = [] <span class="comment">#总的股票市值</span></span><br><span class="line">    rate = [] <span class="comment">#总的收益率</span></span><br><span class="line">    time = [] <span class="comment">#日期</span></span><br><span class="line">    i = <span class="number">0</span></span><br><span class="line">    <span class="keyword">for</span> date <span class="keyword">in</span> histData1.date:</span><br><span class="line">        date = TransfDate2(date)</span><br><span class="line">        time.append(date)</span><br><span class="line">        money.append(data1.成本[i] + data2.成本[i])</span><br><span class="line">        fee.append(data1.手续费[i] + data2.手续费[i])</span><br><span class="line">        market.append(data1.市值[i] + data2.市值[i])</span><br><span class="line">        <span class="comment">#计算收益率</span></span><br><span class="line">        rate.append(market[i]/money[i] - <span class="number">1.0</span>)</span><br><span class="line">        i = i + <span class="number">1</span></span><br><span class="line">    data = pd.DataFrame(&#123;</span><br><span class="line">    <span class="string">&quot;日期&quot;</span>:time,</span><br><span class="line">    <span class="string">&quot;成本&quot;</span>:money,</span><br><span class="line">    <span class="string">&quot;手续费&quot;</span>:fee,</span><br><span class="line">    <span class="string">&quot;市值&quot;</span>:market,</span><br><span class="line">    <span class="string">&quot;收益率&quot;</span>:rate</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="keyword">return</span> data</span><br></pre></td></tr></table></figure>
<p>再把总的收益率也画到一个图里看看。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#将收益率数据合并，算出总的持仓数据</span></span><br><span class="line">    data_total = MergeData(data_300, data_nas, df_300_hist, df_nas_hist)</span><br><span class="line">    plt.figure()</span><br><span class="line">    plt.plot(data_300.收益率, label = <span class="string">&quot;300etf&quot;</span>)</span><br><span class="line">    plt.plot(data_nas.收益率, label = <span class="string">&quot;nasetf&quot;</span>)</span><br><span class="line">    plt.plot(data_total.收益率, label = <span class="string">&quot;etf&quot;</span>)</span><br><span class="line">    plt.legend(loc = <span class="string">&quot;upper right&quot;</span>)</span><br><span class="line">    plt.savefig(<span class="string">&quot;收益率.png&quot;</span>)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0085-etfinverstment/15.jpg"><br>可以看到同时定投两个市场的指数的确可以平衡风险。数据的收集处理就到这里了。接下来就是数据分析啦，作为一篇公众号文章，已经太长了，就下回分解吧。       <br>几点说明：     <br>1.我本职是一名牙医，编程是我的爱好，以前用得最多的是C/C++（不过也只是写一些几千行的小程序），python用的时间不长，所以代码里好多C的味道。      <br>2.写本文是因为crossin编程教室公众号搞了个征稿活动，正好我也打算用python分析一下自己近一年的etf定投数据，就想着把分析过程记录下来，不是说分享就是最好的学习吗？       <br>3.我学习的体会，这种带着问题在做中学，是要比那种一本书或者一个课程从头看到尾要好一些，在这个过程中会碰到各种各样想不到的问题，就想办法解决或者去搜。写程序也是这样，开始只是一个想法：我要分析自己的ETF定投数据，接着就慢慢拆问题：怎么收集数据，需要哪些数据，数据如何处理得到自己想要的数据，如何分析……每个问题又可以拆成更多的问题，直到问题小到可以直接解决。这是计算机的思维方法，也可以用到其它领域，比如我自己的专业领域。       <br>4.本文的主要参考资料：《Python for Data Analysis》，Pandas库作者写的，对，是英文版的。再多说一句，能读原文的最好读原文，其实没那么难的。我读原文书的想法是来自于我自己的专业：口腔医学。以前除了教科书，其它专业书我是基本不看的，看不下去（最主要还是没兴趣）。后来想把自己专业搞好了，开始看书，发现很多书翻译过来要么是比较老的版本了，要么根本就没有翻译的，最重要的是专业书都是厚本厚本的，死贵了。后来发现一个搜英文书的网站：b-ok，很多专业书都能找到英文电子版，还往往是最新的。于是下了很多口腔专业的电子书，上班就在诊室电脑上看，看着看着我发现，看原文也没那么难。这个过程不太长的，就两三个月。从此我又有了一个习惯：看到翻译过来的新书，想看，用英文书名去搜，往往能找到电子版。       <br>5.本文的代码已经上传到github里：<a target="_blank" rel="noopener" href="https://github.com/zwdnet/etfdata">https://github.com/zwdnet/etfdata</a> 后期如果写新的内容，可能会开新的分支。       <br>6.我自己开了个博客：<a href="https://zwdnet.github.io/">https://zwdnet.github.io</a> 还有一个微信订阅号：赵瑜敏的口腔医学学习园地，二维码在最后。主要都是口腔医学的东西，而且不是科普，是给牙医同行看的。所以不是同行的话可以不用看了。谢谢！       <br><strong>最后声明：本文只是探讨python数据处理技术，不构成投资建议。投资有风险，入市需谨慎。</strong><br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg"></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欢迎打赏！感谢支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/mm_facetoface_collect_qrcode_1542944836634.png" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/1542944857770.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/ETF/" rel="tag"># ETF</a>
          
            <a href="/tags/%E6%8A%95%E8%B5%84%E7%90%86%E8%B4%A2/" rel="tag"># 投资理财</a>
          
            <a href="/tags/%E5%AE%9A%E6%8A%95/" rel="tag"># 定投</a>
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
            <a href="/tags/%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/" rel="tag"># 数据分析</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/01/12/%E3%80%8A%E7%89%99%E5%91%A8%E5%88%AE%E6%B2%BB%E5%9F%BA%E7%A1%80%E4%B8%8E%E9%AB%98%E7%BA%A7%E6%A0%B9%E9%9D%A2%E5%88%AE%E6%B2%BB%E3%80%8B%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B014-%E6%A8%A1%E5%9D%974%E4%BD%BF%E7%94%A8%E5%8F%A3%E9%95%9C/" rel="next" title="《牙周刮治基础与高级根面刮治》读书笔记14:模块4使用口镜">
                <i class="fa fa-chevron-left"></i> 《牙周刮治基础与高级根面刮治》读书笔记14:模块4使用口镜
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/01/17/%E3%80%8A%E7%89%99%E5%91%A8%E5%88%AE%E6%B2%BB%E5%9F%BA%E7%A1%80%E4%B8%8E%E9%AB%98%E7%BA%A7%E6%A0%B9%E9%9D%A2%E5%88%AE%E6%B2%BB%E3%80%8B%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B015-%E6%A8%A1%E5%9D%975%EF%BC%9A%E5%89%8D%E7%89%99%E5%8C%BA%E5%9F%9F%E7%9A%84%E6%89%8B%E6%8C%87%E6%94%AF%E7%82%B9/" rel="prev" title="《牙周刮治基础与高级根面刮治》读书笔记15:模块5：前牙区域的手指支点">
                《牙周刮治基础与高级根面刮治》读书笔记15:模块5：前牙区域的手指支点 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTA2Mi8xNzU4Nw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%20%7C%7C%20archive">
              
                  <span class="site-state-item-count">452</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">544</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">本站版权归赵瑜敏所有，如欲转载请与本人联系。</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">1225.8k</span>
  
</div>









<div>
  <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1275447216'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s11.cnzz.com/z_stat.php%3Fid%3D1275447216%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));</script>
</div>

        







  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1275447216&web_id=1275447216" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

  
</body>
</html>
